import Taro, { useCallback, useState, useEffect } from '@tarojs/taro'
import { View, Image, Text, ScrollView } from '@tarojs/components'
import { AtSearchBar, AtTabs, AtTabsPane, AtIcon } from 'taro-ui'
import classnames from 'classnames'
import Loading from '../../components/Loading/Loading'
import Music from '../../components/Music/Music'
import WhiteSpace from '../../components/WhiteSpace/WhiteSpace'
import { setKeywordInHistory, formatCount, formatNumber, formatTimeStampToTime } from '../../utils/index'
import { connect } from '@tarojs/redux'
import { setIsplaying } from '../../redux/actions'
import { search, checkMusic, getvideoUrl, mvUrl } from '../../api/base'
import './index.scss'
const tabList = [{ title: '单曲' }, { title: '歌单' }, { title: '视频' }, { title: '歌手' }, { title: '专辑' }, { title: '用户' }, { title: 'MV' }]
function SearchResult(props) {
  const { dispatch, recentTab, isPlaying, currentSongInfo, canPlayList } = props
  const [keywords, setKeywords] = useState<string>(this.$router.params.keywords)
  const [currentTab, setCurrentTab] = useState<number>(0)
  const [list, setList] = useState<any>([])
  const [hasMore, setHasMore] = useState<boolean>(true)
  const [isload, setIsload] = useState<boolean>(true)
  const togglePlay = useCallback((bool) => {
    dispatch(setIsplaying(bool))
  }, [])
  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: `${keywords}的搜索结果`
    })
  }, [keywords])
  useEffect(() => {
    setList([])
    setHasMore(true)
    setIsload(true)
    switch (currentTab) {
      case 0:
        getSongList()
        break
      case 1:
        getPlayList()
        break
      case 2:
        getVideoList()
        break
      case 3:
        getArtistList()
        break
      case 4:
        getAlbumList()
        break
      case 5:
        getUserList()
        break
      case 6:
        getMvList()
        break
    }
  }, [currentTab])
  const getSongList = useCallback(() => {
    if (!hasMore) {
      return
    }

    search({ keywords, type: 1, limit: 30, offset: list.length }).then((res) => {
      let temp = res.result.songs.map((item) => {
        item.al = item.album
        item.ar = item.artists
        return item
      })
      setList((list) => list.concat(temp))
      setHasMore(res.result.songCount > list.concat(temp).length)
      setIsload(false)
    })
  }, [keywords])

  const getPlayList = useCallback(() => {
    if (!hasMore) {
      return
    }
    search({ keywords, type: 1000, limit: 30, offset: list.length }).then((res) => {
      setList((list) => list.concat(res.result.playlists))
      setHasMore(res.result.playlistCount > list.concat(res.result.playlists).length)
      setIsload(false)
    })
  }, [keywords])
  const getVideoList = useCallback(() => {
    if (!hasMore) {
      return
    }
    search({ keywords, type: 1014, limit: 30, offset: list.length }).then((res) => {
      setList((list) => list.concat(res.result.videos))
      setHasMore(res.result.videoCount > list.concat(res.result.videos).length)
      setIsload(false)
    })
  }, [keywords])
  const getMvList = useCallback(() => {
    if (!hasMore) {
      return
    }
    search({ keywords, type: 1004, limit: 30, offset: list.length }).then((res) => {
      setList((list) => list.concat(res.result.mvs))
      setHasMore(res.result.mvCount > list.concat(res.result.mvs).length)
      setIsload(false)
    })
  }, [keywords])
  const getArtistList = useCallback(() => {
    if (!hasMore) {
      return
    }
    search({ keywords, type: 100, limit: 30, offset: list.length }).then((res) => {
      setList((list) => list.concat(res.result.artists))
      setHasMore(res.result.artistCount > list.concat(res.result.artists).length)
      setIsload(false)
    })
  }, [keywords])
  const getUserList = useCallback(() => {
    if (!hasMore) {
      return
    }
    search({ keywords, type: 1002, limit: 30, offset: list.length }).then((res) => {
      setList((list) => list.concat(res.result.userprofiles))
      setHasMore(res.result.userprofileCount > list.concat(res.result.userprofiles).length)
      setIsload(false)
    })
  }, [keywords])
  const getAlbumList = useCallback(() => {
    if (!hasMore) {
      return
    }
    search({ keywords, type: 10, limit: 30, offset: list.length }).then((res) => {
      setList((list) => list.concat(res.result.albums))
      setHasMore(res.result.albumCount > list.concat(res.result.albums).length)
      setIsload(false)
    })
  }, [keywords])
  const searchResult = useCallback(() => {
    setKeywordInHistory(keywords)
    setKeywords
  }, [keywords])
  const formatDuration = useCallback((ms) => {
    // @ts-ignore
    let minutes = formatNumber(parseInt(ms / 60000))
    // @ts-ignore
    let seconds = formatNumber(parseInt((ms / 1000) % 60))
    return `${minutes}:${seconds}`
  }, [])
  const playSong = useCallback(async (id) => {
    let { success, message } = await checkMusic({ id })
    if (success) {
      Taro.navigateTo({
        url: `/pages/songDetail/index?id=${id}`
      })
    } else {
      Taro.showToast({
        title: message,
        icon: 'none'
      })
    }
  }, [])
  const goPlayListDetail = useCallback((item) => {
    Taro.navigateTo({
      url: `/pages/playListDetail/index?id=${item.id}&name=${item.name}`
    })
  }, [])
  const goVideoDetail = useCallback(async (id, type) => {
    console.log(1)

    let bool = false
    if (type === 'mv') {
      let { data } = await mvUrl({ id })
      data.url && (bool = true)
    } else {
      let { urls } = await getvideoUrl({ id })
      urls.length && (bool = true)
    }
    if (bool) {
      Taro.navigateTo({
        url: `/pages/videoDetail/index?id=${id}&type=${type}`
      })
    } else {
      Taro.showToast({
        title: `该${type === 'mv' ? 'mv' : '视频'}暂无版权播放`,
        icon: 'none'
      })
    }
  }, [])
  return (
    <View className={classnames('result', { musicbox: !!currentSongInfo.name })}>
      {currentSongInfo.id ? (
        <Music
          songInfo={{
            currentSongInfo,
            isPlaying,
            canPlayList
          }}
          isHome={true}
          onUpdatePlayStatus={togglePlay}
        />
      ) : null}
      <AtSearchBar
        actionName="搜一下"
        value={keywords}
        onChange={(e) => setKeywords(e.trim())}
        onActionClick={() => {
          searchResult()
        }}
        onConfirm={() => {
          searchResult()
        }}
        focus={true}
        className="search__input"
        fixed={true}
      />
      <View className="result-content">
        <AtTabs
          current={currentTab}
          scroll
          tabList={tabList}
          onClick={(e) => {
            setCurrentTab(e)
          }}
        >
          <AtTabsPane current={currentTab} index={0}>
            {isload ? (
              <Loading />
            ) : (
              <ScrollView
                onScrollToLower={() => {
                  getSongList()
                }}
                scrollY
                className="result-scroll"
              >
                {list.length == 0 ? <View className="result-nodata">暂无数据</View> : null}
                {list.map((e) => (
                  <View
                    className="result-music flex middle"
                    onClick={() => {
                      playSong(e.id)
                    }}
                  >
                    <View className="cell-main">
                      <View className="xxl mb10">{e.name}</View>
                      <View className="col-hui l"> {`${e.ar[0] ? e.ar[0].name : ''} - ${e.al.name}`}</View>
                    </View>
                    <View className="fa fa-ellipsis-v col-hui xl"></View>
                  </View>
                ))}
              </ScrollView>
            )}
          </AtTabsPane>
          <AtTabsPane current={currentTab} index={1}>
            {isload && currentTab != 1 ? (
              <Loading />
            ) : (
              <ScrollView
                onScrollToLower={() => {
                  getPlayList()
                }}
                scrollY
                className="result-scroll"
              >
                {list.length == 0 ? <View className="result-nodata">暂无数据</View> : null}
                {list.map((e) => (
                  <View
                    className="result-music flex middle"
                    onClick={() => {
                      goPlayListDetail(e)
                    }}
                  >
                    <Image className="list-pic" src={e.coverImgUrl}></Image>
                    <View className="cell-main">
                      <View className="xxl  mb10">{e.name}</View>
                      <View className="col-hui l">
                        {e.trackCount}首音乐by {e.creator.nickname} {formatCount(e.playCount)}次
                      </View>
                    </View>
                  </View>
                ))}
              </ScrollView>
            )}
          </AtTabsPane>

          <AtTabsPane current={currentTab} index={2}>
            {isload && currentTab != 2 ? (
              <Loading />
            ) : (
              <ScrollView
                onScrollToLower={() => {
                  getVideoList()
                }}
                scrollY
                className="result-scroll"
              >
                {list.length == 0 ? <View className="result-nodata">暂无数据</View> : null}
                {list.map((e) => (
                  <View
                    className="result-music flex middle"
                    onClick={() => {
                      goVideoDetail(e.vid, 'video')
                    }}
                  >
                    <View className="result-videobox">
                      <Image className="list-movie" src={e.coverUrl}></Image>
                      <View className="movie-tag">
                        <Text className="at-icon at-icon-play"></Text>
                        <Text>{formatCount(e.playTime)}</Text>
                      </View>
                    </View>

                    <View className="cell-main">
                      <View className="xxl row2  mb10">{e.title}</View>
                      <View className="col-hui l">
                        {formatDuration(e.durationms)} by {e.creator[0].userName}
                      </View>
                    </View>
                  </View>
                ))}
              </ScrollView>
            )}
          </AtTabsPane>
          <AtTabsPane current={currentTab} index={3}>
            {isload && currentTab != 3 ? (
              <Loading />
            ) : (
              <ScrollView
                onScrollToLower={() => {
                  getArtistList()
                }}
                scrollY
                className="result-scroll"
              >
                {list.length == 0 ? <View className="result-nodata">暂无数据</View> : null}
                {list.map((e) => (
                  <View
                    className="result-music flex middle"
                    onClick={() => {
                      goVideoDetail(e.vid, 'video')
                    }}
                  >
                    <Image className="list-avatar" src={e.picUrl}></Image>

                    <View className="cell-main xl">
                      {e.name}
                      {e.alias[0] ? `（${e.alias[0]}）` : ''}
                    </View>
                  </View>
                ))}
              </ScrollView>
            )}
          </AtTabsPane>
          <AtTabsPane current={currentTab} index={4}>
            {isload && currentTab != 4 ? (
              <Loading />
            ) : (
              <ScrollView
                onScrollToLower={() => {
                  getAlbumList()
                }}
                scrollY
                className="result-scroll"
              >
                {list.length == 0 ? <View className="result-nodata">暂无数据</View> : null}
                {list.map((e) => (
                  <View className="result-music flex middle">
                    <Image className="list-pic" src={e.picUrl}></Image>
                    <View className="cell-main">
                      <View className="xxl mb10">{e.name}</View>
                      <View className="col-hui l">
                        {e.artist.name} {e.containedSong ? `包含单曲：${e.containedSong}` : formatTimeStampToTime(e.publishTime)}
                      </View>
                    </View>
                  </View>
                ))}
              </ScrollView>
            )}
          </AtTabsPane>
          <AtTabsPane current={currentTab} index={5}>
            {isload && currentTab != 5 ? (
              <Loading />
            ) : (
              <ScrollView
                onScrollToLower={() => {
                  getUserList()
                }}
                scrollY
                className="result-scroll"
              >
                {list.length == 0 ? <View className="result-nodata">暂无数据</View> : null}
                {list.map((e) => (
                  <View className="result-music flex middle">
                    <Image className="list-avatar" src={e.avatarUrl}></Image>

                    <View className="cell-main xl">
                      <View className="flex middle ">
                        <View className="mr10"> {e.nickname}</View>
                        {e.gender === 1 ? (
                          <AtIcon prefixClass="fa" value="mars" size="12" color="#5cb8e7"></AtIcon>
                        ) : (
                          <AtIcon prefixClass="fa" value="venus" size="12" color="#f88fb8"></AtIcon>
                        )}
                      </View>
                      <View className="col-hui l">{e.signature}</View>
                    </View>
                  </View>
                ))}
              </ScrollView>
            )}
          </AtTabsPane>
          <AtTabsPane current={currentTab} index={6}>
            {isload && currentTab != 6 ? (
              <Loading />
            ) : (
              <ScrollView
                onScrollToLower={() => {
                  getMvList()
                }}
                scrollY
                className="result-scroll"
              >
                {list.length == 0 ? <View className="result-nodata">暂无数据</View> : null}
                {list.map((e) => (
                  <View
                    className="result-music flex middle"
                    onClick={() => {
                      goVideoDetail(e.id, 'mv')
                    }}
                  >
                    <View className="result-videobox">
                      <Image className="list-movie" src={e.cover}></Image>
                      <View className="movie-tag">
                        <Text className="at-icon at-icon-play"></Text>
                        <Text>{formatCount(e.playCount)}</Text>
                      </View>
                    </View>

                    <View className="cell-main">
                      <Text className="xl  row2 mb5">{e.name}</Text>
                      <View className="col-hui l">
                        {formatDuration(e.duration)} by {e.artists[0].name}
                      </View>
                    </View>
                  </View>
                ))}
              </ScrollView>
            )}
          </AtTabsPane>
        </AtTabs>
      </View>
    </View>
  )
}
SearchResult.config = {
  navigationBarTitleText: '搜索'
}
export default connect(
  function mapStateToProps(state) {
    return state
  },
  function mapDispatchToProps(dispatch) {
    return { dispatch }
  }
)(SearchResult)
